package website.seamonster.ethegg.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import website.seamonster.ethegg.dataobject.User;
import website.seamonster.ethegg.enums.ResultEnum;
import website.seamonster.ethegg.exception.EthException;
import website.seamonster.ethegg.repository.ChickenRepository;
import website.seamonster.ethegg.repository.UserRepository;
import website.seamonster.ethegg.utils.PrCodeUtils;

import java.sql.Timestamp;

/**
 * Created by 罗海量
 * 2018-07-22 22:33
 */
@lombok.extern.slf4j.Slf4j
@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ChickenRepository chickenRepository;

    /**
     * 判断购买的数量是否超过该用户孵化圈上限数-鸡的数目
     * @param buyerUserId   购买者ID
     * @param buyCnt        购买蛋的数量
     * @return
     */
    public Boolean isHatchEnough(String buyerUserId, Integer buyCnt){
        return buyCnt <= this.getFreeHatchNum(buyerUserId);
    }

    /**
     * 该用户最大鸡圈数
     * @param userId
     * @return
     */
    public Integer getMaxHatchNum(String userId){
        User u = userRepository.findOne(userId);
        return u.getMaxHatch();
    }

    /**
     * 该用户空闲鸡圈数
     * @param userId
     * @return
     */
    public Integer getFreeHatchNum(String userId){
        int chickenCount = chickenRepository.getCountByUserId(userId);
        return this.getMaxHatchNum(userId) - chickenCount;
    }

    /**
     * 根据推广码查找所属用户
     * @param prCode
     * @return
     */
    public User getUserByPrCode(String prCode){
        if(prCode == null)
            return null;
        User prUser = userRepository.findFirstByPrCode(prCode);
        if (prUser == null) {
            throw new EthException(ResultEnum.PRCODE_NOT_VALID);
        }else{
            //用Java Web服务器的时间
            Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis());
            if (currentTimestamp.after(prUser.getPrEndTime())){
                //推广码过期
                throw new EthException(ResultEnum.PRCODE_NOT_VALID);
            }
        }
        return prUser;
    }

    //获取推广码（如果推广码已过期，重新生成一个）
    @Transactional
    public String getPrCode(String userId){
        User u = userRepository.findOne(userId);
        Timestamp endTime = u.getPrEndTime();
        //用Java Web服务器的时间
        Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis());
        if (endTime==null || currentTimestamp.after(endTime)){
            Timestamp nextEndTime = new Timestamp(System.currentTimeMillis() + 3600000L);
            //更新(生成)推广码
            String newPrCode = null;
            do {
                newPrCode = PrCodeUtils.genPrCode();
            }while(userRepository.findFirstByPrCode(newPrCode)!=null);
            u.setPrCode(newPrCode);
            u.setPrActiveTime(currentTimestamp);
            u.setPrEndTime(nextEndTime);
            User userUpdate = userRepository.save(u);
            return userUpdate.getPrCode();
        } else {
            return u.getPrCode();
        }


    }

}
